// 初始化云数据库
let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
// 连接数据集合
const DBSigin = db.collection('db_sigin')
const DBUser = db.collection('db_user')
const DBMessage = db.collection('db_message')

// 把数据库函数挂在模块系统对象下（暴露api接口）
module.exports = {
  // 添加每日一言
  async addMessageFunc(data = {}) {
    let {
      message,
      openid
    } = data;
    if (message) {
      let res = await DBMessage.where(data).get()
      // console.log('yyy:', res);
      if (res.data.length == 0) {
        return DBMessage.add({
          data: {
            openid,
            result: {
              message
            }
          }
        }).then(
          content => {
            console.log('xxxx:', content)
          }
        )
      }

    }
  },
  // 查询签到
  querySiginFunc(year, month, day, openid) {
    return DBSigin.where({
      year,
      month,
      day,
      openid
    }).get()
  },
  // 添加签到
  addSiginFunc(year, month, day, openid) {
    return DBSigin.add({
      data: {
        year,
        month,
        day,
        openid
      }
    })
  },
  // 个人所有签到
  listSiginFunc(openid) {
    return DBSigin.where({
      openid
    }).get()
  },
  // 查询用户是否注册登录
  queryUserOnFunc(openid) {
    return DBUser.where({
      openid
    }).get()
  },
  // 修改用户昵称
  updateUserNickFunc(openid, nickName, _id) {
    // console.log({
    //   openid,
    //   nickName,
    //   _id
    // })
    return DBUser
      // .doc(openid)
      .where({
        openid: 'oM_L90ONFmBTU7_zeKzoFCo7cQrU'
      })
      .update({
        data: {
          nickName: nickName
        }
      })
  },
  // 签到次数
  async siginCountFunc(openid) {
    var openid =  openid || wx.getStorageSync('openid')
    return await DBSigin.where({openid}).count()
  }
}